package com.pingpang.redis.service;

import java.util.Set;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

@Service
public class RedisService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 添加数据
     * @param key
     * @param value
     */
    public void set(String key, Object value) {
    	delete(key);
        //更改在redis里面查看key编码问题
        RedisSerializer redisSerializer = new  StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        ValueOperations<String, Object> vo =  redisTemplate.opsForValue();
        vo.set(key, value);
    }

    /**
     * 获取数据
     * @param key
     * @return
     */
    public Object get(String key) {
        ValueOperations<String, Object> vo =  redisTemplate.opsForValue();
        return vo.get(key);
    }
    
    /**
     * 删除数据
     * @param key
     * @return
     */
    public boolean delete(String key) {
    	return redisTemplate.delete(key);
    }
    
    
    /**
     * 删除数据匹配前缀
     * @param prex
     * @return
     */
    public void deletePrex(String prex) {
    	Set<String> keys = redisTemplate.keys(prex);
        if (null!=keys && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
    
    /**
     * 统计数量
     * @param prex
     * @return
     */
    public int getCountPrex(String prex) {
    	Set<String> keys = redisTemplate.keys(prex);
    	 if (null!=keys && !keys.isEmpty()) {
    		 return keys.size();
    	 }else {
    		 return 0;
    	 }
    }
}
